﻿using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Minecraft.TableConfigGenerator
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
			
		}

		public static string GetCSVConfigSbr(List<string> nameList, List<string> installGeneratorStrList)
		{
			StringBuilder sbr = new StringBuilder();
			sbr.Append(@"
using Minecraft.Config.Csv.CsvCls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Minecraft.Config
{
	/// <summary>
	/// Csv配置
	/// </summary>
	public partial class CsvConfig
	{
" +
GetListStr(nameList)
+ @"
" +
GetDictStr(nameList)
+ @"
" +
GetDictFuncStr(nameList)
+ @"
" +
GetDictSingleStr(nameList)
+ @"
		/// <summary>
		/// csv配置文件所在目录
		/// </summary>
		public static string Folder
		{
			get
			{
				return Path.Combine(""Csv"", ""CsvFile"");
			}
		}
		/// <summary>
		/// Csv安装
		/// </summary>
		public static void Install()
		{
			List<CsvHelper.CsvInstallInfo> installInfoList = new List<CsvHelper.CsvInstallInfo>();

" +
GetInstallListStr(nameList)
+ @"
" +
GetInstallDictStr(nameList)
+ @"
			if (installInfoList.Any())
			{
				installInfoList.ForEach(item =>
				{
					if (JsonConfig.Value.IsConsoleWrite)
					{
						Console.ForegroundColor = ConsoleColor.Black;
						Console.BackgroundColor = ConsoleColor.White;
						Console.WriteLine();
						//只是粗略的判断
						Console.WriteLine($"" ▲▲▲▲▲▲  csv安装失败：{item.Filepath}，请更新配置文件和Model类"");
						Console.ResetColor();
					}
				});
			}
			InstallAfter();
		}
	}
}
");
			return sbr.ToString();
		}


		private void btnSelectPath_Click(object sender, EventArgs e)
		{
			folderBrowserDialog.ShowDialog();
			var path = folderBrowserDialog.SelectedPath;
			tbxFolderPath.Text = path;
		}

		List<string> GetOrderbyPaths(List<string> csvFilePaths)
		{
			//(from file in csvFilePaths
			//			orderby file
			//			select file).ToList();

			return csvFilePaths;
		}

		private void btnGenerator_Click(object sender, EventArgs e)
		{
			var dirpath = tbxFolderPath.Text;
			if (string.IsNullOrWhiteSpace(dirpath))
			{
				MessageBox.Show("请选择文件夹");
				return;
			}
			string csvClsFolder = Path.Combine(dirpath, "CsvCls");
			//清空指定目（csvFolder）下的所有文件以及文件夹
			if (Directory.Exists(csvClsFolder))
			{
				Directory.Delete(csvClsFolder, true);
			}
			Directory.CreateDirectory(csvClsFolder);

			List<string> nameList = new List<string>();
			//生成list
			List<string> listGeneratorStrList = new List<string>();
			//生成Install
			List<string> installGeneratorStrList = new List<string>();

			//获取csvfile目录文件下的所有配置文件
			var csvFilePaths = Directory.GetFiles(CsvConfig.Folder).ToList();

			//csvFilePaths = GetOrderbyPaths(csvFilePaths);

			foreach (var csvFilePath in csvFilePaths)
			{
				//生成类
				StringBuilder classGeneratorSbr = new StringBuilder();

				var columnNames = CsvHelper.GetTableColumnNameList(csvFilePath);
				var filenameWithoutExt = Path.GetFileNameWithoutExtension(csvFilePath);
				var listName = $"{string.Join("_", filenameWithoutExt.Split('_').ToList().Skip(1).ToArray()).ToLower()}List";
				classGeneratorSbr.AppendLine($"namespace Minecraft.Config.Csv.CsvCls");
				classGeneratorSbr.AppendLine($"{{");
				classGeneratorSbr.AppendLine($"{GetTab(1)}public partial class {filenameWithoutExt}");
				classGeneratorSbr.AppendLine($"{GetTab(1)}{{");
				foreach (var columnName in columnNames)
				{
					classGeneratorSbr.AppendLine($"{GetTab(2)}public string {columnName};");
				}
				classGeneratorSbr.AppendLine($"{GetTab(1)}}}");
				classGeneratorSbr.AppendLine($"}}");

				var classGeneratorSbrStr = classGeneratorSbr.ToString();

				listGeneratorStrList.Add($"public static List<{filenameWithoutExt}> {listName} = new List<{filenameWithoutExt}>();");

				nameList.Add(filenameWithoutExt);

				installGeneratorStrList.Add($"CsvHelper.InstallList(Path.Combine(Folder, \"{Path.GetFileName(csvFilePath)}\"), out {listName}, installInfoList);");

				string newFileName = Path.Combine(csvClsFolder, filenameWithoutExt) + ".cs";

				FileHelper.Write(newFileName, classGeneratorSbrStr, Encoding.UTF8);
			}

			var sbr2Str = GetCSVConfigSbr(nameList, installGeneratorStrList);

			FileHelper.Write(Path.Combine(dirpath, "CSVConfig") + ".cs", sbr2Str, Encoding.UTF8);



			string Folder = Path.Combine("Csv", "CsvFile");
			List<CsvHelper.CsvInstallInfo> installInfoList = new List<CsvHelper.CsvInstallInfo>();
			Dictionary<string, Mod_Attribute> attributeDict = new Dictionary<string, Mod_Attribute>();
			CsvHelper.InstallDict(Path.Combine(Folder, "Mod_Attribute.csv"), out attributeDict, installInfoList);
			//配置表合法性判断
			var repeatList = new List<Mod_Attribute>();
			var distinctList = new List<Mod_Attribute>();
			//var attributeList = CsvConfig.attributeList.OrderBy(m => m.Id_Convert).ToList();
			var attributeList = attributeDict.Select(m => m.Value).OrderBy(m => m.Id_Convert).ToList();
			foreach (var attribute in attributeList)
			{
				if (!distinctList.Any(m => m.Id_Convert == attribute.Id_Convert || m.Attribute_name == attribute.Attribute_name))
				{
					distinctList.Add(attribute);
				}
				else
				{
					repeatList.Add(attribute);
				}
			}
			if (distinctList.Count() < attributeList.Count())
			{
				MessageBox.Show($"属性配置表的id或者名称有重复，请联系策划，重复的id或名称：" +
					$"{repeatList.Select(m => new { id = m.Id, name = m.Attribute_name }).JsonSerialize()}");
				return;
			}

			var generateStr = GetGenerateStr(attributeList);

			FileHelper.Write(Path.Combine(dirpath, "EnumAttribute") + ".cs", generateStr, Encoding.UTF8);


			MessageBox.Show("生成成功");
			System.Diagnostics.Process.Start(dirpath);
		}

		string GetGenerateStr(List<Mod_Attribute> attributeList)
		{
			StringBuilder sbr = new StringBuilder();
			sbr.Append(@"
namespace Minecraft.Model
{
	/// <summary>
	/// 属性枚举（枚举值来源于属性配置表）（该枚举以服务器为准）
	/// </summary>
	public enum EnumAttribute
	{
" + GetAttrListStr(attributeList) + @"
	}
}
");
			return sbr.ToString();
		}

		string GetAttrListStr(List<Mod_Attribute> list)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				stringBuilder.AppendLine(GetTab(2) + $"/// <summary>");
				stringBuilder.AppendLine(GetTab(2) + $"/// {item.Attribute_name}");
				stringBuilder.AppendLine(GetTab(2) + $"/// </summary>");
				stringBuilder.AppendLine(GetTab(2) + $"{item.Type} = {item.Id_Convert},");
			});
			return stringBuilder.ToString();
		}

		public static string GetTab(int num)
		{
			string str = "";
			for (int i = 0; i < num; i++)
			{
				str += "	";
			}
			return str;
		}

		public static string GetListStr(List<string> list, int tabNum)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				stringBuilder.AppendLine(GetTab(tabNum) + item);
			});
			return stringBuilder.ToString();
		}

		public static string GetListStr(List<string> list)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				var listName = $"{string.Join("_", item.Split('_').ToList().Skip(1).ToArray()).ToLower()}";
				stringBuilder.AppendLine(GetTab(2) + $"//public static List<{item}> {listName}List = new List<{item}>();");
			});
			return stringBuilder.ToString();
		}

		public static string GetDictStr(List<string> list)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				var listName = $"{string.Join("_", item.Split('_').ToList().Skip(1).ToArray()).ToLower()}";
				stringBuilder.AppendLine(GetTab(2) + $"private static Dictionary<string, {item}> {listName}Dict = new Dictionary<string, {item}>();");
			});
			return stringBuilder.ToString();
		}

		public static string GetDictFuncStr(List<string> list)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				var listName = $"{string.Join("_", item.Split('_').ToList().Skip(1).ToArray()).ToLower()}";
				stringBuilder.AppendLine(GetTab(2) + $"public static Dictionary<string, {item}> Get{listName}Dict()");
				stringBuilder.AppendLine(GetTab(2) + $"{{");
				stringBuilder.AppendLine(GetTab(3) + $"return {listName}Dict;");
				stringBuilder.AppendLine(GetTab(2) + $"}}");
			});
			return stringBuilder.ToString();
		}
		public static string GetDictSingleStr(List<string> list)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				var listName = $"{string.Join("_", item.Split('_').ToList().Skip(1).ToArray()).ToLower()}";
				stringBuilder.AppendLine(GetTab(2) + $"public static {item} Get{item}InfoById(string id)");
				stringBuilder.AppendLine(GetTab(2) + $"{{");
				stringBuilder.AppendLine(GetTab(3) + $"{listName}Dict.TryGetValue(id, out {item} obj);");
				stringBuilder.AppendLine(GetTab(3) + $"return obj;");
				stringBuilder.AppendLine(GetTab(2) + $"}}");
			});
			return stringBuilder.ToString();
		}
		public static string GetInstallListStr(List<string> list)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				var listName = $"{string.Join("_", item.Split('_').ToList().Skip(1).ToArray()).ToLower()}";
				stringBuilder.AppendLine(GetTab(3) + $"//CsvHelper.InstallList(Path.Combine(Folder, \"{item}.csv\"), out {listName}List, installInfoList);");
			});
			return stringBuilder.ToString();
		}

		public static string GetInstallDictStr(List<string> list)
		{
			StringBuilder stringBuilder = new StringBuilder();
			list.ForEach(item =>
			{
				var listName = $"{string.Join("_", item.Split('_').ToList().Skip(1).ToArray()).ToLower()}";
				stringBuilder.AppendLine(GetTab(3) + $"CsvHelper.InstallDict(Path.Combine(Folder, \"{item}.csv\"), out {listName}Dict, installInfoList);");
			});
			return stringBuilder.ToString();
		}
	}
}
